'use strict';

const Controller = require('../lib/controller');

module.exports = class TrackbackController extends Controller {
  async index() {

    switch (String(this.ctx.request.query.act)) {
      case 'list':
        // View Comment List
        await this.trackbackList();
        break;
      case 'delete':
        await this.trackbackDelete();
        break;
      default:
        if (!this.ctx.request.body.url || !this.ctx.request.body.id) {
          await this.trackbackResponse(1, 'Invalid Parameter');
        } else if (this.ctx.app.theCache.settings.enableTrackbackIn != 1) {
          await this.trackbackResponse(1, 'Trackback Disabled');
        } else {
          await this.trackbackSave();
        }
    }
  }

  // Output Trackback List ////////////////////////////////////////////////////////
  async trackbackList() {
    let sqlWHERE = '';
    let strURLPrefix = '?act=list';
    let arrKeywords = '';

    // Check current page number
    if (this.ctx.request.query.page) {
      this.ctx.request.query.page = this.ctx.helper.checkInt(this.ctx.request.query.page);
      if (this.ctx.request.query.page <= 0) {
        this.ctx.request.query.page = 1;
      }
    } else {
      this.ctx.request.query.page = 1;
    }

    // Check category id
    if (this.ctx.request.query.cat) {
      this.ctx.request.query.cat = this.ctx.helper.checkInt(this.ctx.request.query.cat);
      if (this.ctx.request.query.cat > 0) {
        sqlWHERE += ' AND tLog.log_catID=' + this.ctx.request.query.cat;
        strURLPrefix += '&amp;cat=' + this.ctx.request.query.cat;
      }
    }

    // Check article id
    if (this.ctx.request.query.id) {
      this.ctx.request.query.id = this.ctx.helper.checkInt(this.ctx.request.query.id);
      if (this.ctx.request.query.id > 0) {
        sqlWHERE += ' AND tTB.log_id=' + this.ctx.request.query.id;
        strURLPrefix += '&amp;id=' + this.ctx.request.query.id;
      }
    }

    // Check if has search keywords
    if (this.ctx.request.query.q) {
      arrKeywords = this.ctx.request.query.q.split(' ');
      for (let i = 0; i < this.ctx.request.query.q.length; i++) {
        if (this.ctx.helper.lengthW(arrKeywords[i]) > 2) {
          sqlWHERE += " AND (tTB.tb_title LIKE '%" + this.ctx.helper.checkStr(arrKeywords[i]) + "%' OR tTB.tb_excerpt LIKE '%" + this.ctx.helper.checkStr(arrKeywords[i]) + "%')";
        }
      }
      strURLPrefix += '&amp;q=' + this.ctx.request.query.q;
    }

    // Check if has highlight keywords
    if (this.ctx.request.query.hl) {
      arrKeywords = this.ctx.request.query.hl.split(' ');
      strURLPrefix += '&amp;hl=' + this.ctx.request.query.hl;
    }

    // Load Trackbacks from DB
    let trackbacks;
    let entryCount;
    const entryPerPage = this.ctx.app.theCache.settings.listEntryPerPage;
    const strSQL = 'SELECT tTB.*, tLog.log_authorID, tLog.log_title FROM blog_article tLog, blog_trackback tTB WHERE tLog.log_id=tTB.log_id ' + sqlWHERE + ' ORDER BY tTB.tb_time DESC';

    trackbacks = await this.ctx.app.connBlog.query(strSQL, entryPerPage, this.ctx.request.query.page, false);
    if (!trackbacks) {
      trackbacks = [];
      entryCount = 0;
    } else {
      entryCount = await this.ctx.app.connBlog.recordCount;
      for (let i = 0; i < trackbacks.length; i++) {
        trackbacks[i] = { id: trackbacks[i].tb_id,
          log_id: trackbacks[i].log_id,
          log_title: trackbacks[i].log_title,
          log_authorID: trackbacks[i].log_authorid,
          title: trackbacks[i].tb_title,
          url: trackbacks[i].tb_url,
          blog: trackbacks[i].tb_blog,
          excerpt: trackbacks[i].tb_excerpt,
          time: new Date(Number(trackbacks[i].tb_time)),
          IP: trackbacks[i].tb_ip,
        };
      }
    }

    // Output Trackback List
    const data = {
      strTitle: this.ctx.__('trackbacks'),
      trackbacks,
      intEntryCount: entryCount,
      intEntryPerPage: entryPerPage,
      intCurrentPage: this.ctx.request.query.page,
      intCategory: this.ctx.request.query.cat,
      strURLPrefix,
      arrKeywords,
      input: this.ctx.request.query,
    };
    await this.ctx.render('trackback/trackback.ejs', data);
  }

  // Save New Trackback ////////////////////////////////////////////////////////
  async trackbackSave() {
    const tbEntry = {
      log_id: this.ctx.request.body.id,
      url: this.ctx.request.body.url,
      title: this.ctx.request.body.title,
      excerpt: this.ctx.request.body.excerpt,
      blog: this.ctx.request.body.blog_name,
    };

    if (this.ctx.helper.countURL(tbEntry.excerpt) > this.ctx.app.theCache.settings.maxCommentURLCount) {
      return await this.trackbackResponse(1, 'Excerpt contains too many urls');
    }

    // These function calls look really horrible
    tbEntry.log_id = this.ctx.helper.checkInt(tbEntry.log_id);
    tbEntry.url = this.ctx.helper.trim(this.ctx.helper.wordFilter(this.ctx.helper.checkURL(tbEntry.url)));
    tbEntry.title = this.ctx.helper.trim(this.ctx.helper.wordFilter(this.ctx.helper.trimHTML(this.ctx.helper.trimUBB(tbEntry.title))));
    tbEntry.excerpt = this.ctx.helper.trim(this.ctx.helper.wordFilter(this.ctx.helper.trimHTML(this.ctx.helper.trimUBB(tbEntry.excerpt))));
    tbEntry.blog = this.ctx.helper.trim(this.ctx.helper.wordFilter(this.ctx.helper.trimHTML(this.ctx.helper.trimUBB(tbEntry.blog))));


    if (tbEntry.title == '') tbEntry.title = tbEntry.url;

    // Better Leave the error messages below in English
    if (!tbEntry.log_id) {
      return await this.trackbackResponse(1, 'Invalid Article ID');
    }
    if (tbEntry.url == '') {
      return await this.trackbackResponse(1, 'Source URL is Blank');
    }
    if (tbEntry.url == false || tbEntry.title == false || tbEntry.excerpt == false || tbEntry.blog == false) {
      return await this.trackbackResponse(1, 'Content contains blocked words');
    }

    let tmpA = await this.ctx.app.connBlog.query('SELECT Count(log_ID) as i FROM blog_article WHERE log_locked=false AND log_mode<4 AND log_ID=' + tbEntry.log_id);
    if (!tmpA || !tmpA.length || (tmpA[0].i == 0)) {
      return await this.trackbackResponse(1, 'Article does not exist or is locked');
    }
    tmpA = await this.ctx.app.connBlog.query("SELECT Count(tb_ID) as i FROM blog_trackback WHERE tb_Title='" + this.ctx.helper.checkStr(tbEntry.title) + "' AND tb_Excerpt='" + this.ctx.helper.checkStr(tbEntry.excerpt) + "'");
    if (tmpA.length && (tmpA[0].i > 0)) {
      return await this.trackbackResponse(1, 'Trackback is already saved');
    }

    // Saving trackback
    const arrInsert = {
      log_id: tbEntry.log_id,
      tb_url: tbEntry.url,
      tb_title: tbEntry.title,
      tb_excerpt: tbEntry.excerpt,
      tb_blog: tbEntry.blog,
      tb_ip: this.ctx.theUser.IP,
    };
    await this.ctx.app.connBlog.insert('blog_trackback', arrInsert);

    // Update counters
    await this.ctx.app.connBlog.updateSQL('blog_article', 'log_trackbackCount=log_trackbackCount+1', 'log_id=' + tbEntry.log_id);
    await this.ctx.app.connBlog.updateSQL('blog_settings', 'set_value0=set_value0+1', "set_name='counterTrackback'");
    await this.ctx.app.theCache.updateArticleCounter(tbEntry.log_id, 'trackback', 1);
    await this.ctx.app.theCache.updateGlobalCounter('counterTrackback', 1);

    // Sent OK Response
    await this.trackbackResponse(0);
  }

  // Trackback response
  async trackbackResponse(intFlag, strMessage) {
    this.ctx.set('Content-Type', 'text/xml');

    let body = '<?xml version="1.0" encoding="iso-8859-1"?><response><error>' + intFlag + '</error>';
    if (intFlag == 1) {
      body += '<message>' + strMessage + '</message>';
    }
    body += '</response>';

    this.ctx.body = body;
  }

  // Delete Trackback ////////////////////////////////////////////////////////
  async trackbackDelete() {
    if (this.ctx.theUser.rights.delete < 1) {
      // Check User Right - without DB Query
      return await this.ctx.response.redirectMessage(
        this.ctx.__('error'),
        this.ctx.__('no_rights'),
        this.ctx.__('goback'),
        'javascript:window.history.back();',
        false,
        'errorbox'
      );

    }

    let strError = '';
    let arrData = [];

    this.ctx.request.query.id = this.ctx.helper.checkInt(this.ctx.request.query.id);
    if (!this.ctx.request.query.id) {
      strError = this.ctx.__('invalid_parameter');
    } else {
      // Check user right again
      arrData = await this.ctx.app.connBlog.query('SELECT tLog.log_id,tLog.log_authorID,tTB.tb_id FROM blog_article tLog,blog_trackback tTB WHERE tLog.log_id=tTB.log_id AND tTB.tb_id=' + this.ctx.request.query.id, 1, 1);
      if (arrData) {
        arrData = arrData[0];
        if (this.ctx.theUser.id != arrData.log_authorid || this.ctx.theUser.rights.delete < 2) {
          strError = this.ctx.__('no_rights');
        }
      } else {
        strError = this.ctx.__('trackback_not_found');
      }
    }

    if (strError != '') {
      return await this.ctx.response.redirectMessage(
        this.ctx.__('error'),
        strError,
        this.ctx.__('goback'),
        'javascript:window.history.back();',
        false,
        'errorbox'
      );

    }

    await this.ctx.app.connBlog.doDelete('blog_trackback', 'tb_id=' + this.ctx.request.query.id);
    await this.ctx.app.connBlog.updateSQL('blog_article', 'log_trackbackCount=log_trackbackCount-1', 'log_id=' + arrData.log_id);
    await this.ctx.app.connBlog.updateSQL('blog_settings', 'set_value0=set_value0-1', "set_name='counterTrackback'");
    await this.ctx.app.theCache.updateArticleCounter(this.ctx.request.query.id, 'trackback', -1);
    await this.ctx.app.theCache.updateGlobalCounter('counterTrackback', -1);

    return await this.ctx.response.redirectMessage(
      this.ctx.__('done'),
      this.ctx.__('trackback_delete_done'),
      this.ctx.__('redirect'),
      'article.asp?id=' + arrData.log_id,
      true,
      'messagebox'
    );

  }
};
